package groovyhelper;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiFile;
import com.intellij.lang.Commenter;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class GroovyCommentByLineCommentAction extends GroovyBaseOverrideAction {

    void groovyActionPerformed(AnActionEvent anActionEvent, Editor editor, Project project, PsiFile psiFile) {
        SelectionModel selectionModel = editor.getSelectionModel();
        int start = selectionModel.getSelectionStart();
        int selectionEnd = selectionModel.getSelectionEnd();
        String text = editor.getDocument().getText();
        int startOfLine = text.lastIndexOf('\n', start) + 1;
        if (selectionEnd > startOfLine && text.charAt(selectionEnd -1) == '\n') {
            selectionEnd--;
        }
        String selection = text.substring(startOfLine, selectionEnd);
        if (checkForUncomment(selection)) {
            Pattern p = Pattern.compile("^(\\s*)//", Pattern.MULTILINE);
            selection = p.matcher(selection).replaceAll("$1");
        } else {
            selection = "//" + selection.replaceAll("\n", "\n//");
        }
        substitute(editor, startOfLine, selectionEnd, selection, project, 0);
    }

    private boolean checkForUncomment(String selection) {
        Pattern pattern = Pattern.compile("^\\s*(//)?", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(selection);
        boolean found = false;
        while (matcher.find()) {
            found = true;
            String s = matcher.group(1);
            if (s==null) {
                return false;
            }
        }
        return found;
    }
}
